Tkinter是能將Python程式碼變成圖形化介面的內建GUI函式庫,方便又好上手:
在開始接觸 Python GUI 開發之前,已經習慣了命令列介面的程式,接觸到GUI簡直就是既期待又害怕受傷害。(我大概已經知道自己將會卡在「哪個鈕是對應哪個位置」的這種狀況了🤣)
一開始學的GRADIO個人覺得是蠻好玩的,介面也長得比較可愛;
後來學了Tkinter覺得有種千禧年的復古風格,看看這個簡單的打招呼介面:
好想在旁邊配一個古早微軟Word裡的那根迴紋針Clippit...
不過簡單也是一種優點!我把學習心得整理下來,順便督促自己複習。
import tkinter as tk
window = tk.Tk() # 建立主視窗
window.title("標題") # 設定標題
window.geometry("300x200") # 設定大小 (寬x高)
window.mainloop() # 開啟視窗主迴圈
🏷️ 常用元件有:
Label
:顯示文字或圖片Button
:按鈕互動Entry
:單行文字輸入Text
:多行文字輸入Frame
:容器,用來整理版面剛接觸 Tkinter 的時候,最困惑的就是「版面配置」:
pack()
:讓元件顯示出來,要計算行列grid()
:像 Excel 表格,容易掌控位置➔ 較推薦使用,版面也較整齊place()
:精確定位,但維護麻煩方法 | 版面控制 | 優點 | 缺點 |
---|---|---|---|
pack() | 自動排列 | 快速、簡單 | 彈性低、複雜版面不好用 |
grid() | 行列排列 | 精準、整齊 | 多層嵌套版面可能需要注意 row/column 設定 |
place() | 絕對座標 | 自由、精確 | 維護麻煩、對視窗縮放不友善 |
pack()
的寫法特色:-元件自動依序垂直(或水平)排列
-簡單快速,但版面彈性有限
-要調整間距靠 padx / pady
(padx:水平間距,意思是元件左右各加多少空白)
(pady:垂直間距,意思是元件上下各加多少空白)
import tkinter as tk
from tkinter import messagebox
def greet():
messagebox.showinfo("歡迎", f"Hello, {entry.get()}!")
root = tk.Tk()
root.title("pack 範例")
tk.Label(root, text="請輸入你的名字:").pack(pady=5)
entry = tk.Entry(root)
entry.pack(pady=5)
tk.Button(root, text="送出", command=greet).pack(pady=5)
root.mainloop()
grid()
的寫法特色:-元件按行列排列,像 Excel 表格
-控制位置精準,易於整齊排版
-支援 columnspan / rowspan 跨列或跨行
import tkinter as tk
from tkinter import messagebox
def greet():
messagebox.showinfo("歡迎", f"Hello, {entry.get()}!")
root = tk.Tk()
root.title("grid 範例")
tk.Label(root, text="請輸入你的名字:").grid(row=0, column=0, padx=5, pady=5)
entry = tk.Entry(root)
entry.grid(row=0, column=1, padx=5, pady=5)
tk.Button(root, text="送出", command=greet).grid(row=1, column=0, columnspan=2, pady=5)
root.mainloop()
place()
的寫法特色:-精確控制元件座標(x, y)與大小(width, height)
-適合做自由布局或繪圖界面
-維護困難,視窗大小改變時可能需要手動調整
import tkinter as tk
from tkinter import messagebox
def greet():
messagebox.showinfo("歡迎", f"Hello, {entry.get()}!")
root = tk.Tk()
root.title("place 範例")
root.geometry("300x100") # 設定視窗大小
tk.Label(root, text="請輸入你的名字:").place(x=10, y=10) # 要設定座標
entry = tk.Entry(root)
entry.place(x=120, y=10, width=150)
tk.Button(root, text="送出", command=greet).place(x=100, y=50)
root.mainloop()
-Radiobutton:讓使用者用滑鼠進行「單選」的按鈕物件
-CheckButton:多選
-Listbox:清單選單
import tkinter as tk
from tkinter import messagebox
def show_choice():
messagebox.showinfo("選擇結果", f"你選擇了: {var.get()}")
root = tk.Tk()
root.title("RadioButton 範例")
var = tk.StringVar(value="蘋果") # 預設選項
tk.Label(root, text="請選擇水果:").pack()
tk.Radiobutton(root, text="蘋果", variable=var, value="蘋果").pack(anchor="w")
tk.Radiobutton(root, text="香蕉", variable=var, value="香蕉").pack(anchor="w")
tk.Radiobutton(root, text="橘子", variable=var, value="橘子").pack(anchor="w")
tk.Button(root, text="送出", command=show_choice).pack(pady=5)
root.mainloop()
選一個水果🍎-->RadioButton
選擇障礙(可複選)-->CheckButton
選項更多的時候-->Listbox 可以往下捲動
除了按鈕之外,tkinter也有圖像處理跟進階元件,像是畫布、滑桿、文字訊息... ...等等,我還要再花時間練習!
-要動手實作
GUI 不是只有看文件就會,實際敲程式、看到畫面動起來才是學習的關鍵。
(而且過太多天沒複習的時候就敲不出來了TwT)
-可以練習做小互動程式
例如:打招呼、選水果,聽起來很弱,但還是很需要練;看網友說可以做一些小遊戲,我下次也要來挑戰